package middleware

import (
	"github.com/goravel/framework/auth"
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/errors"
	"github.com/goravel/framework/facades"
	"goravel/app/services"
)

func JwtAuth() http.Middleware {
	return func(ctx http.Context) {
		token := ctx.Request().Header("Authorization", "")
		if len(token) <= 8 {
			services.NewApiService(ctx).Abort401("认证失败，token无效")
			return
		}
		token = token[7:]
		_, err := facades.Auth(ctx).Parse(token)
		is := errors.Is(err, auth.ErrorTokenExpired)
		if is {
			services.NewApiService(ctx).Abort401("认证失败，token过期")
			return
		}
		if err != nil {
			services.NewApiService(ctx).Abort401("认证失败，token解析错误")
			return
		}
		// 服务端踢出登录的情况下，去redis中判断有没有这个token，如果没有则表示被踢出，返回验证失败
		if !facades.Cache().Has("jwt_token:" + token) {
			services.NewApiService(ctx).Abort401("认证失败，token不存在")
			return
		}
		ctx.Request().Next()
	}
}
